package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.Setmeal;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishFlavorMapper;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealDishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorMapper dishFlavorMapper;

    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    /**
     * 新增菜品（同时保存口味信息）
     * @param dishDTO
     */
    @Transactional
    @Override
    public void save(DishDTO dishDTO) {
        //0.开启事务
        //1.构造菜品基本信息，保存数据到菜品dish表中
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);    //拷贝属性值
        dishMapper.insert(dish);

        //2.构造口味列表信息，保存数据到口味dish_flavor表中
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() > 0) {
            //2.1 补充dish_id字段，为了关系菜品
            flavors.forEach(dishFlavor -> {
                dishFlavor.setDishId(dish.getId());
            });
            //2.2 批量插入
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 分页查询--基于分页插件
     * @param dishPageQueryDTO
     * @return
     */
    @Override
    public PageResult page(DishPageQueryDTO dishPageQueryDTO) {
        //1.设置分页参数
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());

        //2.调用mapper的列表查询
        Page<DishVO> dishVOPage = dishMapper.pageQurey(dishPageQueryDTO);

        //3.封装PageResult结果对象，并返回
        return new PageResult(dishVOPage.getTotal(), dishVOPage.getResult());
    }

    @Transactional
    @Override
    public void delete(List<Long> ids) {
        // 0.开启事务
        // 1.启售中的菜品不能删除,查dish
        ids.forEach(id -> {
            Dish dish = dishMapper.selectById(id);
            if (dish.getStatus().equals(StatusConstant.ENABLE)) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }
        });

        // 2.被套餐关联的菜品不能删除，根据菜品id查setmeal_dish
        ids.forEach(id -> {
            Integer count = setmealDishMapper.countByDishId(id);
            if (count > 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }
        });

        // 3.先删菜品
        dishMapper.deleteBatch(ids);

        // 4.再删口味,根据菜品id
        dishFlavorMapper.deleteBatch(ids);
    }

    /**
     * 根据id查询菜品和口味
     * @param id
     * @return
     */
    @Override
    public DishVO getDish(Long id) {
        DishVO dishVO = new DishVO();
        //1.根据id查询菜品基本信息，将基本信息赋值给dishVO
        Dish dish = dishMapper.selectById(id);
        BeanUtils.copyProperties(dish, dishVO);

        //2.查询口味列表，将口味信息赋值给dishVO
        List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(id);
        dishVO.setFlavors(flavors);
        return dishVO;
    }

    /**
     * 修改菜品
     * @param dishDTO
     */
    @Transactional
    @Override
    public void update(DishDTO dishDTO) {
        //0.开启事务
        //1.调用dishMapper的更新方法，修改菜品基本信息
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.update(dish);

        //2.更新口味数据（可以新增、修改、删除口味数据）
        //2.1 为了操作简单，可以先清空原来当前菜品的所有口味数据
        dishFlavorMapper.deleteByDishId(dishDTO.getId());
        //2.2 直接新增前端传递过来的口味列表
        List<DishFlavor> flavors = dishDTO.getFlavors();
        if (flavors != null && flavors.size() >0){
            //关联dish_id
            flavors.forEach(flavor ->{
                flavor.setDishId(dishDTO.getId());
            });
            dishFlavorMapper.insertBatch(flavors);
        }
    }

    /**
     * 菜品启售停售
     * @param status
     * @param id
     */
    @Transactional
    @Override
    public void startOrStop(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.update(dish);

        // 如果是停售操作，还需要将包含当前菜品的套餐也停售
        if (status.equals(StatusConstant.DISABLE)) {
            // 联表查询setmeal、dish、setmeal_dish
            Setmeal setmeal = setmealMapper.getByDishId(id);
            if (setmeal != null) {  //有关联的套餐才需要执行update操作，注意判空处理，否则NPE
                setmeal.setStatus(StatusConstant.DISABLE);
                setmealMapper.update(setmeal);
            }
        }
    }

    /**
     * 根据分类id查询菜品列表
     * @param categoryId
     * @return
     */
    @Override
    public List<Dish> getByCategoryId(Long categoryId, String name) {
        Dish dish = Dish.builder().categoryId(categoryId).name(name).build();
        return dishMapper.getByCategoryId(dish);
    }

    /**
     * 条件查询菜品和口味
     * @param dish
     * @return
     */
    public List<DishVO> listWithFlavor(Dish dish) {
        List<Dish> dishList = dishMapper.getByCategoryId(dish);

        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish d : dishList) {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(d,dishVO);

            //根据菜品id查询对应的口味
            List<DishFlavor> flavors = dishFlavorMapper.selectByDishId(d.getId());

            dishVO.setFlavors(flavors);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }
}
